package com.neo.office.server.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neo.office.server.config.data.Result;
import com.neo.office.server.domain.entity.Menu;
import com.neo.office.server.domain.entity.MenuRole;
import com.neo.office.server.domain.entity.Role;
import com.neo.office.server.service.MenuRoleService;
import com.neo.office.server.service.MenuService;
import com.neo.office.server.service.RoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限组
 */
@RestController
@RequestMapping("/system/basic/permission")
public class PermissionController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private MenuRoleService menuRoleService;

    @ApiOperation(value = "权限功能-获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRoles(){
        return roleService.list();
    }

    @ApiOperation(value = "权限功能-添加角色")
    @PostMapping("/role")
    public Result addRole(@RequestBody Role role){
        if (!role.getName().startsWith("ROLE_")){
            role.setName("ROLE_" + role.getName());
        }
        if (roleService.save(role)){
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }

    @ApiOperation(value = "权限功能-删除角色")
    @DeleteMapping("/role/{id}")
    public Result deleteRole(@PathVariable Integer id){
        if (roleService.removeById(id)){
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }

    @ApiOperation(value = "权限功能-查询菜单")
    @GetMapping("/menus")
    public List<Menu> getMenuOfPermission(){
        return menuService.getMenuOfPermission();
    }

    @ApiOperation(value = "权限功能-根据角色ID查询菜单ID")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid){
        List<MenuRole> list = menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid",rid));
        return list.stream().map(MenuRole::getMid).collect(Collectors.toList());
    }

    @ApiOperation(value = "权限功能-更新角色菜单")
    @PutMapping("/")
    public Result updateMenuRole(Integer rid,Integer[] mids){
        return menuRoleService.updateMenuRole(rid,mids);
    }

}
